﻿using System.Collections.Generic;
using EnvDTE;
using EnvDTE80;
using Microsoft.Practices.RecipeFramework;

namespace ProjectBase.Guidance.Actions
{
    public class CollapseAction : Action
    {
        public override void Execute()
        {
            var dte = (DTE) GetService(typeof (DTE));
            var dte2 = (DTE2) dte;
            UIHierarchy solutionExplorer = dte2.ToolWindows.SolutionExplorer;

            IList<UIHierarchyItems> nodes = Collapse(solutionExplorer.UIHierarchyItems, -1);
            solutionExplorer.UIHierarchyItems.Expanded = true;
            foreach (UIHierarchyItems uiHierarchyItemse in nodes)
            {
                uiHierarchyItemse.Expanded = true;
            }
        }

        protected virtual IList<UIHierarchyItems> Collapse(UIHierarchyItems items, int level)
        {
            var nodes = new List<UIHierarchyItems>();
            if (level >= 4)
            {
                items.Expanded = false;
                return nodes;
            }

            items.Expanded = true;

            foreach (UIHierarchyItem item in items)
            {
                UIHierarchyItems folder = item.UIHierarchyItems;

                nodes.Add(folder);

                Collapse(folder, level + 1);

                folder.Expanded = false;
            }

            if (level < 1 && nodes.Count > 4)
            {
                nodes[nodes.Count - 4].Expanded = true;
            }

            items.Expanded = false;
            return nodes;
        }

        public override void Undo()
        {
        }
    }
}